package org.wxy.sdk.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Created by wxy on 2018/05/27.
 *
 * @author wxy
 * @date on 2018/05/27 11:32
 */
public class MD5 {

	/**
	 * 转换为十六进制
	 * @return 密码
	 */
	public static String stringToMD5(String string) {
		if (string == null) {
			return "";
		}
		try {
			return md5(string.getBytes("UTF-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return null;
		}
	}


	public static String md5(byte[] md5){
		byte[] hash;
		try {
			hash = MessageDigest.getInstance("MD5").digest(md5);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
			return null;
		}

		StringBuilder hex = new StringBuilder(hash.length * 2);
		for (byte b : hash) {
			if ((b & 0xFF) < 0x10) {
				hex.append("0");
			}
			hex.append(Integer.toHexString(b & 0xFF));
		}
		return hex.toString();
	}

	/**
	 * 计算文件MD5值
	 * @param fileName 文件路径
	 * @return
	 * @throws IOException
	 * @throws NoSuchAlgorithmException
     */
	public static String fileMD5(String fileName) throws IOException, NoSuchAlgorithmException {
		File f = new File(fileName);

		InputStream ins = new FileInputStream(f);

		byte[] buffer = new byte[4*1024];

		MessageDigest md5 = MessageDigest.getInstance("MD5");

		int len;

		while((len = ins.read(buffer)) != -1) {
			md5.update(buffer, 0, len);
		}

		ins.close();

		return toHexString(md5.digest());
	}

	private static char[] hexChar = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

	private static String toHexString(byte[] b) {
		StringBuilder sb = new StringBuilder(b.length * 2);
		for (byte aB : b) {
			sb.append(hexChar[(aB & 0xf0) >>> 4]);
			sb.append(hexChar[aB & 0x0f]);
		}
		return sb.toString();
	}
}
